package com.xxxx.seckill.rocketmq;

import com.alibaba.fastjson.JSON;
import com.xxxx.seckill.pojo.SeckillMessage;
import com.xxxx.seckill.pojo.SeckillOrder;
import com.xxxx.seckill.pojo.User;
import com.xxxx.seckill.service.IGoodsService;
import com.xxxx.seckill.service.IOrderService;
import com.xxxx.seckill.vo.GoodsVo;
import com.xxxx.seckill.vo.RespBean;
import com.xxxx.seckill.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 消费者消费消息
 *
 * @author 刘红申 on 2022/4/6
 * @time 16:22
 */
@Service
@Slf4j
@RocketMQMessageListener(topic = "producer_queue_one", consumerGroup = "consumer_topic_queue_one")
public class MQConsumer implements RocketMQListener<String> {

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IOrderService iOrderService;


    /**
     * 下单操作
     * @param message
     */
    @Override
    public void onMessage(String message) {
        log.info("接收到的消息:" + message);
        SeckillMessage seckillMessage = JSON.parseObject(message, SeckillMessage.class);
        Long goodsId = seckillMessage.getGoodsId();
        User user = seckillMessage.getUser();

        //还是要判断库存的哦
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        if (goodsVo.getStockCount() < 1) {
            return;
        }

        //判断是否重复抢购
        //redis是否重复抢购，也就是这个key是否存在
        SeckillOrder seckillOrder = (SeckillOrder)redisTemplate
                .opsForValue()
                .get("order:" + user.getId() + ":" + goodsId);

        if (seckillOrder != null) {
            return;
        }
        //下单操作
        iOrderService.seckill(user, goodsVo);
    }
}
